/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
Ext.chart.Chart.CHART_URL = '../../../ext3/resources/charts.swf';
Ext.QuickTips.init();
var _pageSize = 20;

var store;
var now = new Date();
var defaultDay = now.add(Date.DAY, -1);
var saveServlet = '../../../servlet/data/RsjSave';
var loadServlet = '../../../servlet/data/RsjLoad';

var fieldName = ['name', 'shortName', 'pointType', 'pointType2', 'date', 'voltageLevelName', 'maxVoltage', 'maxVoltageTime', 'minVoltage', 'minVoltageTime', 'avgVoltage',
    'defaultTotalTime', 'aboveUpperLimitMin', 'aboveUpperLimitNumber', 'underLowerLimitMin', 'underLowerLimitNumber', 'totalRunMin', 'rate', 'dataYear', 'dataMonth', 'dataDay',
    , 'id', 'isOffline', 'deviceId', 'did', 'pointId', "orgCode", "company", "subCompany", "pointArea", "pointPosition", "pointTypeId", "pointType2Id",
    "lowerLimit", "upperLimit", "orgTypeId", "orgTypeName", "voltage", "voltageLevelValue", "voltageLevelId", "voltageLevelName","code","companyCode"];
var fieldLabel = ['测点名称', '单位名称', '测点类别', '电网类别', '日期', '电压等级<br/>(kv)', '最高电压', '最高电压时间', '最低电压', '最低电压时间', '平均电压', '故障时间<br/>（分钟）', "超上限时间<br/>（分钟）", "超上限<br/>次数", "超下限时间<br/>（分钟）", "超下限<br/>次数", '总时间<br/>（分钟）', '合格率（%）'];

var theme = '日数据';

var mergeProperties = function (o, n, override) {
    for (var p in n)
        if (n.hasOwnProperty(p) && (!o.hasOwnProperty(p) || override))
            o[p] = n[p];
};

var basic11 = {columnWidth: .33,
    layout: 'form',
    defaultType: 'textfield',
    items: [
        {
            xtype: 'textfield',
            fieldLabel: '测点名称',
            name: 'name',
            anchor: '95%',
            readOnly: true
        },
        {
            xtype: 'textfield',
            fieldLabel: '单位名称',
            name: 'shortName',
            anchor: '95%',
            readOnly: true
        }
    ]
};

var basic12 = {columnWidth: .33,
    layout: 'form',
    defaultType: 'textfield',
    items: [
        {
            xtype: 'textfield',
            fieldLabel: '测点类别',
            name: 'pointType',
            anchor: '95%',
            readOnly: true
        },
        {
            xtype: 'textfield',
            fieldLabel: '电网类别',
            name: 'pointType2',
            anchor: '95%',
            readOnly: true
        }
    ]
};

var basic13 = {columnWidth: .33,
    layout: 'form',
    defaultType: 'textfield',
    items: [
        {
            xtype: 'textfield',
            fieldLabel: '电压等级(kv)',
            name: 'voltageLevelName',
            anchor: '95%',
            readOnly: true
        },
        {
            xtype: 'textfield',
            fieldLabel: '日期',
            id: 'DataYearMonthDay',
            name: 'dataYearMonthDay',
            anchor: '95%',
            readOnly: true
        }
    ]
};

var basic1 = {
    xtype: 'fieldset',
    title: '基本信息',
    id: 'Basic1',
    autoHeight: true,
    layout: 'column',
    items: [basic11, basic12, basic13]
};


var basic21 = {columnWidth: .33,
    layout: 'form',
    defaultType: 'textfield',
    items: [
        {
            xtype: 'textfield',
            fieldLabel: '最高电压',
            name: 'maxVoltage',
            anchor: '95%'
        },
        {
            xtype: 'textfield',
            fieldLabel: '最低电压',
            name: 'minVoltage',
            anchor: '95%'
        }, {
            xtype: 'textfield',
            fieldLabel: '平均电压',
            name: 'avgVoltage',
            anchor: '95%'
        },
        {
            xtype: 'textfield',
            fieldLabel: '故障时间',
            name: 'defaultTotalTime',
            anchor: '95%'
        }
    ]
};

var basic22 = {columnWidth: .33,
    layout: 'form',
    defaultType: 'textfield',
    items: [
        {
            xtype: 'numberfield',
            fieldLabel: '总时间',
            name: 'totalRunMin',
            id: 'TotalRunMin',
            anchor: '95%',
            listeners: {
                blur: function (o) {
                    var rate = (Ext.getCmp('TotalRunMin').getValue() - (Ext.getCmp('UnderLowerLimitMin').getValue() + Ext.getCmp('AboveUpperLimitMin').getValue())) / Ext.getCmp('TotalRunMin').getValue() * 100;
                    rate = rate.toFixed(3);
                    Ext.getCmp('Rate').setValue(rate);
                }
            }
        },
        {
            xtype: 'numberfield',
            fieldLabel: '合格率（%）',
            id: 'Rate',
            name: 'rate',
            anchor: '95%'
        },
        {
            xtype: 'numberfield',
            fieldLabel: '超上限时间',
            name: 'aboveUpperLimitMin',
            id: 'AboveUpperLimitMin',
            anchor: '95%',
            listeners: {
                blur: function (o) {
                    var rate = (Ext.getCmp('TotalRunMin').getValue() - (Ext.getCmp('UnderLowerLimitMin').getValue() + Ext.getCmp('AboveUpperLimitMin').getValue())) / Ext.getCmp('TotalRunMin').getValue() * 100;
                    rate = rate.toFixed(3);
                    Ext.getCmp('Rate').setValue(rate);
                }
            }
        },
        {
            xtype: 'textfield',
            fieldLabel: '超上限次数',
            name: 'aboveUpperLimitNumber',
            anchor: '95%',
            enable:false,
            value:0
        }
    ]
};

var basic23 = {columnWidth: .33,
    layout: 'form',
    defaultType: 'textfield',
    items: [
        {
            xtype: 'timefield',
            fieldLabel: '最高电压时间',
            id: 'MaxVoltageTime',
            name: 'maxVoltageTime',
            format: 'H:i:s',
            anchor: '95%'
        },
        {
            xtype: 'timefield',
            id: 'MinVoltageTime',
            fieldLabel: '最低电压时间',
            name: 'minVoltageTime',
            format: 'H:i:s',
            anchor: '95%'
        },
        {
            xtype: 'numberfield',
            fieldLabel: '超下限时间',
            name: 'underLowerLimitMin',
            id: 'UnderLowerLimitMin',
            anchor: '95%',
            listeners: {
                blur: function (o) {
                    var rate = (Ext.getCmp('TotalRunMin').getValue() - (Ext.getCmp('UnderLowerLimitMin').getValue() + Ext.getCmp('AboveUpperLimitMin').getValue())) / Ext.getCmp('TotalRunMin').getValue() * 100;
                    rate = rate.toFixed(3);
                    Ext.getCmp('Rate').setValue(rate);
                }
            }
        },
        {
            xtype: 'textfield',
            fieldLabel: '超下限次数',
            name: 'underLowerLimitNumber',
            anchor: '95%',
            enable:false,
            value:0
        }
    ]
};

var basic2 = {
    xtype: 'fieldset',
    title: '数据信息',
    id: 'Basic2',
    autoHeight: true,
    layout: 'column',
    items: [basic21, basic22, basic23]
};

var basic31 = {columnWidth: .167,
    layout: 'form',
    defaultType: 'textfield',
    labelWidth: 40,
    items: [
        {
            xtype: 'textfield',
            fieldLabel: '00时',
            name: 'h00',
            anchor: '95%'
        },
        {
            xtype: 'textfield',
            fieldLabel: '06时',
            name: 'h06',
            anchor: '95%'
        },
        {
            xtype: 'textfield',
            fieldLabel: '12时',
            name: 'h12',
            anchor: '95%'
        },
        {
            xtype: 'textfield',
            fieldLabel: '18时',
            name: 'h08',
            anchor: '95%'
        }
    ]
};

var basic32 = {columnWidth: .167,
    layout: 'form',
    defaultType: 'textfield',
    labelWidth: 40,
    items: [
        {
            xtype: 'textfield',
            fieldLabel: '01时',
            name: 'h01',
            anchor: '95%'
        },
        {
            xtype: 'textfield',
            fieldLabel: '07时',
            name: 'h07',
            anchor: '95%'
        },
        {
            xtype: 'textfield',
            fieldLabel: '13时',
            name: 'h13',
            anchor: '95%'
        },
        {
            xtype: 'textfield',
            fieldLabel: '19时',
            name: 'h19',
            anchor: '95%'
        }
    ]
};

var basic33 = {columnWidth: .167,
    layout: 'form',
    defaults: {// defaults are applied to items, not the container
        xtype: 'textfield',
        anchor: '95%'
    },
    labelWidth: 40,
    items: [
        {
            fieldLabel: '02时',
            name: 'h02',
        },
        {
            fieldLabel: '08时',
            name: 'h08'
        },
        {
            fieldLabel: '14时',
            name: 'h14'
        },
        {
            fieldLabel: '22时',
            name: 'h22'
        }
    ]
};

var basic34 = {columnWidth: .167,
    layout: 'form',
    defaultType: 'textfield',
    labelWidth: 40,
    items: [
        {
            xtype: 'textfield',
            fieldLabel: '03时',
            name: 'h03',
            anchor: '95%'
        },
        {
            xtype: 'textfield',
            fieldLabel: '09时',
            name: 'h09',
            anchor: '95%'
        },
        {
            xtype: 'textfield',
            fieldLabel: '15时',
            name: 'h15',
            anchor: '95%'
        },
        {
            xtype: 'textfield',
            fieldLabel: '21时',
            name: 'h21',
            anchor: '95%'
        }
    ]
};

var basic35 = {columnWidth: .167,
    layout: 'form',
    defaultType: 'textfield',
    labelWidth: 40,
    items: [
        {
            xtype: 'textfield',
            fieldLabel: '04时',
            name: 'h04',
            anchor: '95%'
        },
        {
            xtype: 'textfield',
            fieldLabel: '10时',
            name: 'h10',
            anchor: '95%'
        },
        {
            xtype: 'textfield',
            fieldLabel: '16时',
            name: 'h16',
            anchor: '95%'
        },
        {
            xtype: 'textfield',
            fieldLabel: '22时',
            name: 'h22',
            anchor: '95%'
        }
    ]
};

var basic36 = {columnWidth: .167,
    layout: 'form',
    defaultType: 'textfield',
    labelWidth: 40,
    items: [
        {
            xtype: 'textfield',
            fieldLabel: '05时',
            name: 'h05',
            anchor: '95%'
        },
        {
            xtype: 'textfield',
            fieldLabel: '11时',
            name: 'h11',
            anchor: '95%'
        },
        {
            xtype: 'textfield',
            fieldLabel: '17时',
            name: 'h17',
            anchor: '95%'
        },
        {
            xtype: 'textfield',
            fieldLabel: '23时',
            name: 'h23',
            anchor: '95%'
        }
    ]
};

var basic3 = {
    xtype: 'fieldset',
    title: '24小时电压',
    id: 'Basic3',
    autoHeight: true,
    layout: 'column',
    items: [basic31, basic32, basic33, basic34, basic35, basic36]
};


var type = 1;         //判断打开窗口是进行更新，还是新建。1-新建；2-修改
var updated = false;
var inputForm = new Ext.FormPanel(
        {
            xtype: 'form',
            id: 'input-form',
            bodyStyle: 'padding:15px;background:transparent',
            frame: true,
            border: false,
            url: saveServlet,
            items: [
                basic1, basic2, basic3
            ],
            buttons: [{
                    text: '保存',
                    iconCls: 'icon-save',
                    handler: function () {
                        var submitConfig = {
                            success: function (form, action) {
                                win.hide();
                                store.reload();
                            },
                            failure: function (form, action) {
                                switch (action.failureType) {
                                    case Ext.form.Action.CONNECT_FAILURE:
                                        Ext.Msg.alert('提示', '网络连接失败');
                                        break;
                                    case Ext.form.Action.SERVER_INVALID:
                                        Ext.Msg.alert('提示', action.result.msg);
                                }
                            },
                            params: {}
                        };


                        var did = checkboxSel.getSelected().get('did');
                        var pointId = checkboxSel.getSelected().get('id');
                        var deviceId = checkboxSel.getSelected().get('deviceId');
                        var dataYear = Ext.getCmp('dateFrom').getValue().format('Y');
                        var dataMonth = Ext.getCmp('dateFrom').getValue().format('m');
                        var dataDay = Ext.getCmp('dateFrom').getValue().format('d');

                        submitConfig.params.pointId = pointId;
                        submitConfig.params.deviceId = deviceId;
                        submitConfig.params.dataYear = dataYear;
                        submitConfig.params.dataMonth = dataMonth;
                        submitConfig.params.dataDay = dataDay;
                        if (did === null || did === '') {
                            var r = checkboxSel.getSelected();
                            var orgCode = r.get("orgCode");
                            var company = r.get("company");
                            var subCompany = r.get("subCompany");
                            var station = r.get("shortName");
                            var name = r.get("name");
                            var pointArea = r.get("pointArea");
                            var pointPosition = r.get("pointPosition");
                            var pointTypeId = r.get("pointTypeId");
                            var pointType = r.get("pointType");
                            var pointType2Id = r.get("pointType2Id");
                            var pointType2 = r.get("pointType2");
                            var lowerLimit = r.get("lowerLimit");
                            var upperLimit = r.get("upperLimit");
                            var startStatus = r.get("startStatus");
                            var reportStatus = r.get("reportStatus");
                            var orgTypeId = r.get("orgTypeId");
                            var orgTypeName = r.get("orgTypeName");
                            var voltage = r.get("voltage");
                            var voltageLevelValue = r.get("voltageLevelValue")
                            var voltageLevelId = r.get("voltageLevelId");
                            var voltageLevelName = r.get("voltageLevelName");
                            var pointCode = r.get("code");
                            var companyCode = r.get("companyCode");
                            submitConfig.params.orgCode = orgCode;
                            submitConfig.params.company = company;
                            submitConfig.params.subCompany = subCompany;
                            submitConfig.params.station = station;
                            submitConfig.params.name = name;
                            submitConfig.params.pointArea = pointArea;
                            submitConfig.params.pointPosition = pointPosition;
                            submitConfig.params.pointTypeId = pointTypeId;
                            submitConfig.params.pointType = pointType;
                            submitConfig.params.pointType2Id = pointType2Id;
                            submitConfig.params.pointType2 = pointType2;
                            submitConfig.params.lowerLimit = lowerLimit;
                            submitConfig.params.upperLimit = upperLimit;
                            submitConfig.params.startStatus = startStatus;
                            submitConfig.params.reportStatus = reportStatus;
                            submitConfig.params.orgTypeId = orgTypeId;
                            submitConfig.params.orgTypeName = orgTypeName;
                            submitConfig.params.voltage = voltage;
                            submitConfig.params.voltageLevelValue = voltageLevelValue;
                            submitConfig.params.voltageLevelId = voltageLevelId;
                            submitConfig.params.voltageLevelName = voltageLevelName;
                            submitConfig.params.pointCode = pointCode;
                            submitConfig.params.companyCode = companyCode;                            
                            submitConfig.params.cmd = 'createLock';
                        } else {
                            submitConfig.params.id = did;
                            submitConfig.params.cmd = 'updateLock';
                        }
                        var token1 = new Date().getTime();
                        submitConfig.params.token = token;
                        submitConfig.params.token1 = token1;
                        Ext.getCmp('input-form').getForm().submit(submitConfig);
                    }
                }, {
                    text: '取消',
                    handler: function () {
                        win.hide();
                    }
                }]
        }
);


var win = new Ext.Window({
    layout: 'form',
    width: 800,
    autoHeight: true,
    closeAction: 'hide',
    items: [inputForm]
});

function copyRawData() {
    if (currentOrgCode.length !== 4) {
        Ext.Msg.alert("系统提示", "只允许市级公司进行操作");
        return;
    }
    Ext.MessageBox.confirm('提示', '该操作会删除锁定表中已经修改好的数据。</br>确实要拷贝原始月数据到锁定表吗?', function (btn) {
        if (btn !== "yes")
            return;

        var date = Ext.getCmp('dateFrom').getValue().format('Ymd');

        var reportStatus = -1;
        var range = -1;
        var token1 = new Date().getTime();        
        Ext.Ajax.request({
            url: '../../../servlet/data/LockServlet',
            success: function (response, options) {
                var obj = Ext.decode(response.responseText);
                if (obj.success) {
                    store.reload();
                    Ext.Msg.alert("系统提示", "获取原始数据成功");
                } else {
                    Ext.Msg.alert("系统提示", obj.msg);
                }
            },
            failure: function (response, opts) {
                Ext.Msg.alert('系统提示', '获取原始数据失败，清稍候再试 ' + response.status);
            },
            params: {token:token,token1:token1,lock: lock, cmd: "copyROrg", date: date, reportStatus: reportStatus, range: range}
        });
    });
}

function manualRecall() {
    updated = true;
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("提示", "您还没有选择，需要选择一个记录才能修改");
    } else if (checkboxSel.getSelections().length > 1) {
        Ext.Msg.alert("提示", "您选择了多个记录，只能选择一个记录进行修改");
    } else {
        if (win === null) {
            win = new Ext.Window({
                layout: 'form',
                width: 340,
                autoHeight: true,
                closeAction: 'hide',
                modal: true,
                items: [inputForm]
            });
        }
        type = 2;
        var record = checkboxSel.getSelected();


        Ext.getCmp('input-form').getForm().loadRecord(checkboxSel.getSelected());


        var maxTime = record.get('maxVoltageTime');
        var minTime = record.get('minVoltageTime');
        Ext.getCmp("MaxVoltageTime").setValue(maxTime.substring(11, 19));
        Ext.getCmp("MinVoltageTime").setValue(minTime.substring(11, 19));

        var rate = record.get('rate');
        var rateFloat = parseFloat(rate);
        Ext.getCmp("Rate").setValue(rateFloat.toFixed(3));
        var date = checkboxSel.getSelected().get('date').toString();
        Ext.getCmp('DataYearMonthDay').setValue(date.substr(0, 4) + "年" + date.substr(4, 2) + "月" + date.substr(6, 2) + "日");

        win.setTitle('手工录入' + theme);
        win.show();
    }
}

function batchCreate() {
    Ext.MessageBox.confirm('提示', '该操作将生产当前搜索条件下所有缺失数据。</br>确实要生成无数据监测点的日数据吗?', function (btn) {
        if (btn !== "yes")
            return;

        var myMask = new Ext.LoadMask(Ext.getBody(), {msg: "请稍候..."});
        myMask.show();
        var token1 = new Date().getTime();
        var params = {token:token,token1:token1,cmd: "batchCreate", have: 1, lock: lock};
        mergeProperties(params, store.baseParams);
        
        Ext.Ajax.request({
            url: saveServlet,
            //timeout: 50000,
            success: function (response, options) {
                //alert(response.responseText);
                var obj = Ext.decode(response.responseText);
                if (obj.success) {
                    store.reload();
                } else {
                    Ext.Msg.alert("系统提示", obj.msg);
                }
                myMask.hide();
            },
            failure: function (response, opts) {
                Ext.Msg.alert('系统提示', '生成失败，清稍候再试 ' + response.status);
                myMask.hide();
            },
            params: params
        });
    });
}

var rateSetForm = new Ext.FormPanel(
        {
            xtype: 'form',
            id: 'DayRateSetForm',
            bodyStyle: 'padding:15px;background:transparent',
            frame: true,
            border: false,
            url: '../../../servlet/data/RsjSave',
            items: [
                {
                    xtype: 'label',
                    fieldLabel: '提示',
                    //height:'',
                    text: '该操作将调整合格率至指定值附近（只调整搜索条件下的所有监测点）'
                },
                {
                    xtype: 'datefield',
                    fieldLabel: '数据时间',
                    id: 'DataTime',
                    name: 'dataTime',
                    format: 'Y年m月d日',
                    readOnly: true,
                    //value: now.add(Date.MONTH, -1),
                    anchor: '95%'
                },
                //new tlf.component.PointTypeCombo({value: -1}),
                {
                    xtype: 'numberfield',
                    fieldLabel: '合格率(%)',
                    id: 'RateSetField',
                    name: 'rate',
                    decimalPrecision: 4,
                    allowBlank: false,
                    blankText: '必须填写合格率',
                    maxValue: 100,
                    maxText: '合格率必须小于100%',
                    minValue: 0,
                    minText: '合格率必须大于0',
                    anchor: '95%'
                }
            ],
            buttons: [{
                    text: '确定',
                    iconCls: 'icon-save',
                    handler: function () {
                        var params = {lock: lock, cmd: 'dRateSet'};
                        mergeProperties(params, store.baseParams);
                        var submitConfig = {
                            success: function (form, action) {
                                winRateSet.hide();
                                store.reload();
                                //Ext.Msg.alert("系统提示", action.result.msg);
                            },
                            failure: function (form, action) {
                                switch (action.failureType) {
                                    case Ext.form.Action.CONNECT_FAILURE:
                                        Ext.Msg.alert('系统提示', '网络连接失败');
                                        break;
                                    case Ext.form.Action.SERVER_INVALID:
                                        Ext.Msg.alert('系统提示', action.result.msg);
                                }
                            },
                            params: params
                        };
                        var token1 = new Date().getTime();
                        submitConfig.params.token = token;
                        submitConfig.params.token1 = token1;
                        submitConfig.params.dateTo = Ext.getCmp('DataTime').getValue().format('Ymd');
                        Ext.getCmp('DayRateSetForm').getForm().submit(submitConfig);
                    }
                }, {
                    text: '取消',
                    handler: function () {
                        winRateSet.hide();
                    }
                }]
        }
);

var winRateSet = new Ext.Window({
    title: '设置合格率',
    layout: 'form',
    modal: true,
    width: 400,
    autoHeight: true,
    closeAction: 'hide',
    items: [rateSetForm]
});

function rateSet() {
    if (currentOrgCode.length < 4) {
        Ext.Msg.alert("系统提示", "只允许市级以下公司进行操作");
        return;
    }
    Ext.getCmp("DataTime").setValue(Ext.getCmp("dateFrom").getValue());
    winRateSet.show();
}

var recallForm = new Ext.FormPanel(
        {
            xtype: 'form',
            id: 'RecallForm',
            bodyStyle: 'padding:15px;background:transparent',
            frame: true,
            border: false,
            url: '../../../servlet/task/TaskSave',
            items: [{
                    name: 'pointNames',
                    xtype: 'textarea',
                    id: 'PointNamesRecall',
                    width: 180,
                    height: 200,
                    readOnly: true,
                    disable: true,
                    fieldLabel: '所选监测点',
                    allowBlank: false,
                    blankText: '监测点名称必须填写'
                }
            ],
            buttons: [{
                    text: '确定',
                    iconCls: 'icon-save',
                    handler: function () {
                        var submitConfig = {
                            success: function (form, action) {
                                winRecall.hide();
                                Ext.Msg.alert("系统提示", action.result.msg);
                            },
                            failure: function (form, action) {
                                switch (action.failureType) {
                                    case Ext.form.Action.CONNECT_FAILURE:
                                        Ext.Msg.alert('系统提示', '网络连接失败');
                                        break;
                                    case Ext.form.Action.SERVER_INVALID:
                                        Ext.Msg.alert('系统提示', action.result.msg);
                                }
                            },
                            params: {cmd: 'createRBackflowTask'}
                        };
                        //alert(checkboxSel.getSelections().length);
                        var ids = getIds(checkboxSel.getSelections());
                        var dates = getFields(checkboxSel.getSelections(), 'date');
                        submitConfig.params.deviceIds = ids.deviceIds;
                        submitConfig.params.dates = dates;
                        submitConfig.params.lock = lock;
                        var token1 = new Date().getTime();
                        submitConfig.params.token = token;
                        submitConfig.params.token1 = token1;
                        Ext.getCmp('RecallForm').getForm().submit(submitConfig);
                    }
                }, {
                    text: '取消',
                    handler: function () {
                        winRecall.hide();
                    }
                }]
        }
);
var winRecall = new Ext.Window({
    title: '监测点日数据回灌',
    layout: 'form',
    width: 400,
    autoHeight: true,
    closeAction: 'hide',
    items: [recallForm]
});

function realRecall() {

}

function backflow() {
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("系统提示", "您还没有选择，请选择需要补采的监测点");
    } else {
        //var r = checkboxSel.getSelected();
        var pointNames = getFields(checkboxSel.getSelections(), 'name');
        Ext.getCmp('PointNamesRecall').setValue(pointNames);
        //Ext.getCmp('ReportStatusCombo').setValue();
        winRecall.show();
    }
}

var recallBatchForm = new Ext.FormPanel(
        {
            xtype: 'form',
            id: 'RecallBatchForm',
            bodyStyle: 'padding:15px;background:transparent',
            frame: true,
            border: false,
            url: '../../../servlet/task/TaskSave',
            items: [
                {
                    xtype: 'datefield',
                    fieldLabel: '数据时间',
                    id: 'DataTimeFrom',
                    name: 'dataTimeFrom',
                    format: 'Y年m月d日',
                    readOnly: true,
                    //value: now.add(Date.MONTH, -1),
                    anchor: '95%'
                }, {
                    xtype: 'datefield',
                    fieldLabel: '数据时间',
                    id: 'DataTimeTo',
                    name: 'dataTimeTo',
                    format: 'Y年m月d日',
                    readOnly: true,
                    //value: now.add(Date.MONTH, -1),
                    anchor: '95%',
                    listeners: {
                        select: function (c, date) {
                            Ext.getCmp('DataTimeFrom').setValue(date);
                        }
                    }
                },
                new tlf.component.PointTypeCombo({value: -1})
            ],
            buttons: [{
                    text: '确定',
                    iconCls: 'icon-save',
                    handler: function () {
                        var submitConfig = {
                            success: function (form, action) {
                                winRecallBatch.hide();
                                Ext.Msg.alert("系统提示", action.result.msg);
                            },
                            failure: function (form, action) {
                                switch (action.failureType) {
                                    case Ext.form.Action.CONNECT_FAILURE:
                                        Ext.Msg.alert('系统提示', '网络连接失败');
                                        break;
                                    case Ext.form.Action.SERVER_INVALID:
                                        Ext.Msg.alert('系统提示', action.result.msg);
                                }
                            },
                            params: {lock: lock, cmd: 'createRBatchBackflowTask'}
                        };
                        var token1 = new Date().getTime();
                        submitConfig.params.token = token;
                        submitConfig.params.token1 = token1;
                        submitConfig.params.dateFrom = Ext.getCmp('DataTimeFrom').getValue().format('Ymd');
                        submitConfig.params.dateTo = Ext.getCmp('DataTimeTo').getValue().format('Ymd');
                        Ext.getCmp('RecallBatchForm').getForm().submit(submitConfig);
                    }
                }, {
                    text: '取消',
                    handler: function () {
                        winRecallBatch.hide();
                    }
                }]
        }
);

var winRecallBatch = new Ext.Window({
    title: '批量数据回灌',
    layout: 'form',
    width: 400,
    autoHeight: true,
    closeAction: 'hide',
    items: [recallBatchForm]
});

function backflowBatch() {
    Ext.getCmp('DataTimeFrom').setValue(Ext.getCmp('dateFrom').getValue());
    Ext.getCmp('DataTimeTo').setValue(Ext.getCmp('dateTo').getValue());
    winRecallBatch.show();
}

function manualRemove() {
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("提示", "您还没有选择，需要选择一个记录才能清除");
    } else if (checkboxSel.getSelections().length > 1) {
        Ext.Msg.alert("提示", "您选择了多个记录，只能选择一个记录进行清除");
    } else {

        var pointId = checkboxSel.getSelected().get("id");
        var dataYear = checkboxSel.getSelected().get("dataYear");
        var dataMonth = checkboxSel.getSelected().get("dataMonth");
        var dataDay = checkboxSel.getSelected().get("dataDay");

        if (dataYear === null || dataYear === '') {
            Ext.Msg.alert("系统提示", "该监测点无数据");
            return;
        }


        Ext.MessageBox.confirm('提示', '确实要清除所选记录的数据吗?', function (btn) {
            if (btn !== "yes")
                return;

            var myMask = new Ext.LoadMask(Ext.getBody(), {msg: "请稍候..."});
            myMask.show();
            var token1 = new Date().getTime();
            
            Ext.Ajax.request({
                url: saveServlet,
                //timeout: 50000,
                success: function (response, options) {
                    //alert(response.responseText);
                    var obj = Ext.decode(response.responseText);
                    if (obj.success) {
                        store.reload();
                    } else {
                        Ext.Msg.alert("系统提示", obj.msg);
                    }
                    myMask.hide();
                },
                failure: function (response, opts) {
                    Ext.Msg.alert('系统提示', '删除失败，清稍候再试 ' + response.status);
                    myMask.hide();
                },
                params: {token: token, token1: token1, lock: lock, cmd: "remove", pointId: pointId, dataYear: dataYear, dataMonth: dataMonth, dataDay: dataDay}
            });
        });
    }
}

function removeAll() {

    Ext.MessageBox.confirm('提示', '<font color="#ff0000">确实要清除所有记录的数据吗?<br/>清除后将不可恢复，请谨慎操作！！！</font>', function (btn) {
        if (btn !== "yes")
            return;

        var myMask = new Ext.LoadMask(Ext.getBody(), {msg: "请稍候..."});
        myMask.show();
        
        var token1 = new Date().getTime();        
        var params = {token: token, token1: token1, lock: lock, cmd: "removeAll"};
        mergeProperties(params, store.baseParams);
        Ext.Ajax.request({
            url: saveServlet,
            //timeout: 50000,
            success: function (response, options) {
                //alert(response.responseText);
                var obj = Ext.decode(response.responseText);
                if (obj.success) {
                    store.reload();
                } else {
                    Ext.Msg.alert("系统提示", obj.msg);
                }
                myMask.hide();
            },
            failure: function (response, opts) {
                Ext.Msg.alert('系统提示', '删除失败，清稍候再试 ' + response.status);
                myMask.hide();
            },
            params: params
        });
    });

}

var checkboxSel = new Ext.grid.CheckboxSelectionModel();
var store;
function buildWindow() {
    store = new Ext.data.JsonStore({
        url: loadServlet,
        root: 'data',
        idProperty: 'rn',
        totalProperty: 'count',
        fields: fieldName,
        autoLoad: true,
        baseParams: {lock: lock, cmd: 'general', start: 0, limit: _pageSize, dateFrom: defaultDay.format('Ymd'), dateTo: defaultDay.format('Ymd')}
    });
    tbarPoint = new Ext.Toolbar({
        items: [
            pointTypeCombo, pointType2Combo, voltageLevelCombo, reportCombo, haveCombo
                    , pointText, searchButton
        ]
    });
    tbarPoint.insert(0, {
        xtype: 'datefield',
        id: 'dateFrom',
        format: 'Y年m月d日',
        width: 150,
        value: defaultDay,
        hidden: true,
        listeners: {
            select: function (c, date) {
                beginDate = date.format('Ymd');
                store.baseParams.dateFrom = beginDate;
            }
        }
    }
    );

    tbarPoint.insert(1, {
        xtype: 'datefield',
        id: 'dateTo',
        format: 'Y年m月d日',
        width: 150,
        value: defaultDay,
        listeners: {
            select: function (c, date) {
                beginDate = date.format('Ymd');
                Ext.getCmp('dateFrom').setValue(date);
                store.baseParams.dateFrom = beginDate;
                store.baseParams.dateTo = beginDate;
            }
        }
    }
    );

    var grid = new Ext.grid.GridPanel({
        title: _title,
        store: store,
        sm: checkboxSel,
        columns: [
            checkboxSel,
            new Ext.grid.RowNumberer({width: 40, header: '序号'}),
            {header: 'id', dataIndex: 'id', hidden: true},
            {header: 'PointId', dataIndex: 'pointId', hidden: true},
            {header: 'Code', dataIndex: 'code', hidden: true},
            {header: 'CompanyCode', dataIndex: 'companyCode', hidden: true},
            {header: fieldLabel[0], sortable: true, dataIndex: fieldName[0]},
            {header: fieldLabel[1], width: 80, sortable: true, dataIndex: fieldName[1]},
            {header: fieldLabel[2], width: 60, sortable: true, dataIndex: fieldName[2]},
            {header: '在线', width: 60, sortable: true, dataIndex: 'isOffline'},
            {header: fieldLabel[3], width: 60, sortable: true, dataIndex: fieldName[3]},
            {header: fieldLabel[4], width: 80, sortable: true, dataIndex: fieldName[4]},
            {header: fieldLabel[5], width: 80, sortable: true, dataIndex: fieldName[5]},
            {header: fieldLabel[17], width: 100, sortable: true, dataIndex: 'rate', align: 'right', format: '0.000'},
            {header: fieldLabel[6], width: 80, sortable: true, dataIndex: fieldName[6]},
            {header: fieldLabel[7], width: 100, sortable: true, dataIndex: fieldName[7]},
            {header: fieldLabel[8], width: 80, sortable: true, dataIndex: fieldName[8]},
            {header: fieldLabel[9], width: 100, sortable: true, dataIndex: fieldName[9]},
            {header: fieldLabel[10], width: 80, sortable: true, dataIndex: fieldName[10]},
            {header: fieldLabel[11], width: 80, sortable: true, dataIndex: fieldName[11]},
            {header: fieldLabel[12], width: 80, sortable: true, dataIndex: fieldName[12]},
            //{header: fieldLabel[13], width: 50, sortable: true, dataIndex: fieldName[13]},
            {header: fieldLabel[14], width: 80, sortable: true, dataIndex: fieldName[14]},
            //{header: fieldLabel[15], width: 50, sortable: true, dataIndex: fieldName[15]},
            {header: fieldLabel[16], width: 80, sortable: true, dataIndex: fieldName[16]}
        ],
        loadMask: true,
        tbar: new Ext.Toolbar([
            {
                text: '获取原始数据',
                iconCls: 'icon-linkratio',
                handler: copyRawData,
                hidden: lock === "" ? true : false
            },
            {
                text: '手工录入',
                iconCls: 'icon-linkratio',
                handler: manualRecall
            },
            {
                text: '缺失数据生成',
                iconCls: 'icon-linkratio',
                handler: batchCreate
            }, {
                text: '合格率设置',
                iconCls: 'icon-linkratio',
                handler: rateSet,
                hidden: lock === "" ? true : false
            },
            {
                text: '日数据回灌',
                iconCls: 'icon-linkratio',
                handler: backflow
                        //hidden: lock === "" ? true : false
            }, {
                text: '批量日数据回灌',
                iconCls: 'icon-linkratio',
                handler: backflowBatch
                        // hidden: lock === "" ? true : false
            }, {
                text: '删除数据',
                iconCls: 'icon-linkratio',
                handler: manualRemove,
                hidden: !isSuper
            }, {
                text: '清除数据',
                style: 'font-color:#ff0000',
                iconCls: 'icon-removeAll',
                handler: removeAll,
                hidden: !isSuper
            }
        ]),
        listeners: {
            'render': function () {
                tbarPoint.render(this.tbar);
            }
        },
        bbar: new Ext.PagingToolbar({
            pageSize: _pageSize,
            store: store,
            displayInfo: true,
            displayMsg: '显示记录：{0} - {1}   总记录：{2}',
            emptyMsg: '目前没有信息'
        })
    });

    var applicationUI = new Ext.Viewport({
        layout: "fit",
        items: [
            grid
        ]
    });
}
Ext.onReady(buildWindow);
